//
//  BDNetworkManager.m
//  HSY
//
//  Created by 陈浩 on 2017/4/11.
//  Copyright © 2017年 金开门. All rights reserved.
//

#import "BDNetworkManager.h"
#import <AFNetworking.h>
#import "BDNetworkUtils.h"

@interface BDNetworkManager ()

@property (nonatomic, strong) AFHTTPSessionManager *networkManager;

@end

@implementation BDNetworkManager

+ (instancetype)sharedInstatce{
    static BDNetworkManager *manager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        if (!manager) {
            manager = [[self alloc] init];
        }
    });
    return manager;
}


- (instancetype)init{
    self = [super init];
    if (self) {
        self.hostURL = TEST_GLOBAL_DOMAIN;
        self.fileUrl = TEST_GLOBAL_DOMAIN_FILES_ADDRESS;
        
//        self.hostURL = GLOBAL_DOMAIN;
//        self.fileUrl = GLOBAL_DOMAIN_FILES_ADDRESS;

        //配置AFHTTPSessionManager
        self.networkManager = [AFHTTPSessionManager manager];
        self.networkManager.requestSerializer.timeoutInterval = 30;
    }
    return self;
}

+ (void)POST:(BDRequest *)request success:(BDSuccessHandler)success failure:(BDErrorHandler)failure{
    [[BDNetworkManager sharedInstatce] POST:request success:success failure:failure];
}

- (void)POST:(BDRequest *)request success:(BDSuccessHandler)success failure:(BDErrorHandler)failure{
    if (request.task.state == NSURLSessionTaskStateRunning) {
        [request.task cancel];
        request.task = nil;
    }
    if ([request fileUplaod]) {
        NSURLSessionTask *task = [self.networkManager POST:self.fileUrl parameters:[request buildUrlParams] constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
            //以前的方式相同图片会上传，会穿最前面的一张
            for (int i =0; i<request.files.count; i++) {
                
                BDFileModel *model = request.files[i];
                
                if (model.fileData != nil) {
                    NSData *data = model.fileData;
                    NSString *fileName = [NSString stringWithFormat:@"%@.%@",model.fileType,model.suffix];
                    NSString *mineTyeStr = model.mimeType;
                    
                    [formData appendPartWithFileData:data name:[NSString stringWithFormat:@"%@",model.fileType] fileName:fileName mimeType:mineTyeStr];
                    
                }
                
            }
            
        } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            if (success) {
                BDResponse *response = [BDResponse mj_objectWithKeyValues:responseObject];
                response.encryptDataResult = [responseObject[BD_REQUEST_ENCRYPT_DATA_RESULT] mj_JSONObject];
                success(response);
            }
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            if (failure) {
                failure(error);
            }
        }];
        request.task = task;
    }else{
        NSURLSessionTask *task = [self.networkManager POST:self.hostURL parameters:[request buildUrlParams] progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            if (success) {
                BDResponse *response = [BDResponse mj_objectWithKeyValues:responseObject];
                response.encryptDataResult = [responseObject[BD_REQUEST_ENCRYPT_DATA_RESULT] mj_JSONObject];
                success(response);
            }
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            if (failure) {
                failure(error);
            }
        }];
        request.task = task;
    }
}

+ (void)POST:(BDRequest *)request completionHander:(BDCompletionHandler)completion{
    [[BDNetworkManager sharedInstatce] POST:request completionHander:completion];
}

- (void)POST:(BDRequest *)request completionHander:(BDCompletionHandler)completion{
    [self POST:request success:^(BDResponse *response) {
        if (response.resultCode == BD_REQUEST_CODE_SUCCESS) {
            if (completion) {
                completion(response.encryptDataResult, nil);
            }
        }else{
            if (completion) {
                completion(nil, response.resultMessage);
            }
        }
    } failure:^(NSError *error) {
        if (error.code != NSURLErrorCancelled) {
            if (completion) {
                completion(nil, @"请求失败");
            }
        }else{
            if (completion) {
                completion(nil, nil); //用户取消
            }
        }
    }];
}


@end
